from pyspark.sql import SparkSession, functions as F

if __name__ == '__main__':
    # 构建SparkSession对象
    spark = SparkSession.builder. \
        appName("local[*]"). \
        config("spark.sql.shuffle.partitions", "4"). \
        getOrCreate()
    # appName 设置程序名称
    # config 设置常用属性。可以通过此来设置配置
    # 最后通过getOrCreate 创建 SparkSession对象

    # 从SparkSession中获取SparkContext
    sc = spark.sparkContext

    # TODO 1.加载数据
    df = spark.readStream \
        .format(source="rate") \
        .option("rowPerSecond", "10") \
        .option("ramUpTime", "0s") \
        .option("numPartitions", 1) \
        .load()
    #  rowPerSecond : 每秒生成数据条数
    #  ramUpTime : 每条数据生成时间间隔
    #  numPartitions : 分区数量


    df.printSchema()

    print(type(df))

    # TODO 2.处理数据


    # TODO 3.输出结果
    df.writeStream \
        .format("console") \
        .outputMode("append") \
        .option("truncate",False) \
        .start() \
        .awaitTermination()   # TODO 4.启动并等待结束

    # .outputMode("complete")
    # Complete output mode not supported when there are no streaming aggregations on streaming DataFrames/Datasets;
    # complete输出模式，必须有聚合的操作才能使用

    # TODO 5.关闭资源
    spark.stop()


